<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\user\LoginForm;
use yii\captcha\Captcha;
use common\models\Setting\Setting;
use common\models\member\Member;
use common\models\orders\Orders;
/**
 * Site controller
 */
class SiteController extends BackendController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['captcha', 'login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
		$setting = Setting::findBySql('SELECT value FROM setting where id in(52,53,54)')->asArray()->all();
		$captchaConfig = array(
        'class' => 'zhongkefu\helpers\WanhuCaptcha',
        'height' => $setting[2]['value'],
        'width' => $setting[1]['value'],
        'maxLength' => 4,
        'minLength' => 4,
		'flag' => $setting[0]['value'],
		); 
		
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
			'captcha' => $captchaConfig, 
        ];
    }

    public function actionIndex()
    {
		$province = array();
		$arry="";
		$area="";
		$caiwu="";
		$i=0;
		$time=strtotime(date('Y')."-01-01 00:00:00");//当前年
		$year = date("Y");
		$data = member::findBySql("SELECT count(*) as num,month(FROM_UNIXTIME(created_at)) as m FROM member where created_at<=".time()." and created_at>=".$time." group by month(FROM_UNIXTIME(created_at))")->asArray()->all();

		foreach($data as $key =>$val){
		    $arry .= '{ month: "'.$val["m"].'月", value: '.$val["num"].' },';
		}
		
		//会员地域分布
		
		$minfo = member::findBySql("select ip from member where status=20")->asArray()->all();
		
		foreach($minfo as $k => $v){
			$info = $this->GetIpLookup($v['ip']);
			$province[] = $info['province'];
		} 
		
		$areaval = array_count_values($province);
		foreach($areaval as $key => $val){
			$color=$this->randrgb();
			$area .= '{value: '.$val.',color: "'.$color.'",highlight: "'.$color.'",label: "'.$key.'"},';
		}
		
		
		//以年为单位统计财务状况 状态为2是支付成功
		$odata = orders::findBySql("SELECT sum(paymoney) as total,year(FROM_UNIXTIME(created_at)) as year FROM orders where status=2 group by year(FROM_UNIXTIME(created_at))")->asArray()->all();
		foreach($odata as $key => $val){
			$caiwu .= '{ year: "'.$val["year"].'年", value: '.$val["total"].' },';
		}
		
        return $this->render('index', [
                'data' => $arry,
				'year' => $year,
				'area' => $area,
				'caiwu' => $caiwu,
            ]);
    }
	

    public function actionLogin()
    {
		$setting = Setting::findBySql('SELECT value FROM setting where id = 51')->asArray()->all();
		$data = $setting[0]['value'];
		if(strstr($data,"8")){
			$yanzhengma = true;
		}else{
			$yanzhengma = false;
		}
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
				'yanzhengma' => $yanzhengma,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

	function GetIpLookup($ip = ''){
		if(empty($ip)){
			return 'unkonw'; 
		}
		$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);  
		if(empty($res)){ return false; }
		$jsonMatches = array();
		preg_match('#\{.+?\}#', $res, $jsonMatches);
		if(!isset($jsonMatches[0])){ return false; }
		$json = json_decode($jsonMatches[0], true);
		if(isset($json['ret']) && $json['ret'] == 1){
			$json['ip'] = $ip;
			unset($json['ret']);
		}else{
			return false;  
		}
		return $json;  
	}
	
	function randrgb() 
	{ 
	  $str='0123456789ABCDEF'; 
		$estr='#'; 
		$len=strlen($str); 
		for($i=1;$i<=6;$i++) 
		{ 
			$num=rand(0,$len-1);   
			$estr=$estr.$str[$num];  
		} 
		return $estr; 
	} 

}
